require 'faraday_middleware'
require 'smtpcom_api/request/urls'

module SmtpcomApi
  module Request
    
    include Urls

    API_PATH = '/v1'
    FORMAT   = 'json'
    HTTP_METHODS = [:get, :put, :post, :delete]

    def method_missing(name, *args)
      if HTTP_METHODS.include? name.to_sym
        key    = args[0]
        params = args[1] || {}
        pl = params.delete(:pl)
        _call(name, get_url(key, pl), process_params(params))
      else 
        super
      end
    end

    def respond_to?(name)
      if HTTP_METHODS.include? name.to_sym
        true
      else
        super
      end
    end

    private

      def process_params(params)
        params[:time_start] = params[:time_start].to_i if params[:time_start]
        params[:time_end]   = params[:time_end].to_i   if params[:time_end]
        params
      end

      def get_url(key, pl=[])
        [@api_host, API_PATH, get_path(key, pl), ".#{FORMAT}"].join
      end

      def get_path(key, pl)
        pl = [pl] unless pl.instance_of?(Array)
        pl.map!{|s| CGI.escape(s.to_s).gsub(/\./,'%2E')}
        Urls.const_get(key.to_s.upcase) % pl
      end

      def _call(method, path, params)
        conn = Faraday.new do |c|
          c.request :url_encoded
          #c.response :logger
          c.response :json
          c.response :raise_error          
          c.adapter :net_http
        end
        
        res = conn.send(method, path, params.merge({:api_key => @api_key})).body
        raise "Error #{res["code"]}: #{res["message"]}" unless res['code'] == 0
        res
      end

  end
end